package com.learn.algorithm.list;

/**
 * https://leetcode.cn/problems/add-two-numbers
 */
public class AddTwoLists {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode answer = null;
        ListNode current = null;
        int carry = 0;
        while (l1 != null || l2 != null) {
            int sum = (l1 == null ? 0 : l1.val)
                    + (l2 == null ? 0 : l2.val) + carry;
            int val = sum % 10;
            carry = sum / 10;
            if (answer == null) {
                answer = new ListNode(val);
                current = answer;
            } else {
                current.next = new ListNode(val);
                current = current.next;
            }
            if (l1 != null) l1 = l1.next;
            if (l2 != null) l2 = l2.next;
        }
        if (carry > 0) {
            current.next = new ListNode(carry);
        }
        return answer;
    }
}
